<template>
    <div>
        <form>
            <label for="bookName">书名:</label><input type="text" v-model="bn"><br>
            <label for="author">作者:</label><input type="text" v-model="au"><br>
            <label for="price">价格:</label><input type="number" v-model="bp"><br>
        </form>
        <input type="button" value="确认" @click="btnadd(route.params.id)"><input type="button" value="取消"
            @click="router.push('/')">
    </div>
</template>
<script setup>
import { onMounted, ref } from 'vue';
import { fetchAddDate, fetchSingleData, fetchEditData } from '@/api/http';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter()
const route = useRoute()
const bn = ref('')
const au = ref('')
const bp = ref('')

if (route.params.id) {
    onMounted(async () => {
        let id = route.params.id
        let data = await fetchSingleData(id)
        bn.value = data.data.bookName
        au.value = data.data.author
        bp.value = data.data.price
    })

}

const btnadd = async (id) => {
    if (id) {
        await fetchEditData(id, bn.value, au.value, bp.value)
        alert('修改成功')
    } else {
        await fetchAddDate(bn.value, au.value, bp.value)
        alert('新增成功')

    }
    router.push('/')
}
</script>